package com.dog.view.converter;

import com.dog.view.utils.Messages;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import java.util.Locale;

/**
 * User: Kuttubek Aidaraliev
 * Date: 03.06.2010
 * Time: 11:47:33
 */
public class EnumAsStringConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String s) {
       System.out.println("test param");
       throw new ConverterException();
    }

    @Override
    public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object o) {

        System.out.println(o.getClass());

        FacesContext context = FacesContext.getCurrentInstance();
        String bundleName = context.getApplication().getMessageBundle();
        Locale locale = context.getViewRoot().getLocale();

        String name = null;

        if(o instanceof Enum){
            Enum e = (Enum)o;

            name = Messages.getMessageResourceString(bundleName, e.toString().toLowerCase(Locale.ENGLISH),
                   null, locale);
        }
        else if(o instanceof String){
            String enumString = (String)o;
            System.out.println(enumString);
            name = Messages.getMessageResourceString(bundleName, enumString.toLowerCase(Locale.ENGLISH),
                    null, locale);
        }
        else {
            FacesMessage facesMessage = new FacesMessage("Conversation error occurred. ",
                    "Object must be Enum object.");
                facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
                throw new ConverterException(facesMessage);
        }

        return name;
    }
}
